package com.aiyige.page.detail;

import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.Router;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.eventbus.EventAddFollow;
import com.aiyige.base.eventbus.EventBuySuccess;
import com.aiyige.base.eventbus.EventDeleteFollow;
import com.aiyige.base.eventbus.EventLogin;
import com.aiyige.base.eventbus.EventMomentChanged;
import com.aiyige.im.SessionHelper;
import com.aiyige.logic.user.UserDataManager;
import com.aiyige.model.PlayProgressModel;
import com.aiyige.model.Subject;
import com.aiyige.model.User;
import com.aiyige.model.moment.backup.CommodityBackup;
import com.aiyige.model.moment.backup.CreatorBackup;
import com.aiyige.model.moment.backup.DetailBackup;
import com.aiyige.model.moment.backup.MineBackup;
import com.aiyige.model.moment.backup.PhotoBackup;
import com.aiyige.model.moment.backup.StatisticsBackup;
import com.aiyige.model.moment.backup.TagBackup;
import com.aiyige.model.moment.entity.FavoriteRecord;
import com.aiyige.model.moment.entity.Guarantee;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.model.moment.entity.Praise;
import com.aiyige.model.moment.entity.SinglePhoto;
import com.aiyige.model.moment.entity.SingleVideo;
import com.aiyige.model.moment.entity.VideoCourse;
import com.aiyige.model.request.AddCommentRequest;
import com.aiyige.model.request.FavoriteRequest;
import com.aiyige.model.request.GetCommentsRequest;
import com.aiyige.model.request.PraiseRequest;
import com.aiyige.model.response.CommentResponse;
import com.aiyige.model.sns.Comment;
import com.aiyige.model.sns.Follow;
import com.aiyige.page.detail.adpater.DetailAboutAdapter;
import com.aiyige.page.detail.adpater.DetailAdapter;
import com.aiyige.page.detail.adpater.DetailMoreAdapter;
import com.aiyige.page.detail.adpater.DetailSelectionAdapter;
import com.aiyige.page.detail.decoration.ItemRecyclerViewDivider;
import com.aiyige.page.detail.dialog.DialogSafeguard;
import com.aiyige.page.detail.dialog.VideoCourseFragment;
import com.aiyige.page.login.LoginPage;
import com.aiyige.page.login.callbacks.ILoginCallBack;
import com.aiyige.page.login.model.impl.LoginManager;
import com.aiyige.page.my.download.util.DownloadUtil;
import com.aiyige.page.my.order.dialog.CommonOperationDialog;
import com.aiyige.page.my.order.model.KeyValue;
import com.aiyige.page.pay.util.PayUtil;
import com.aiyige.page.photo.model.Photo;
import com.aiyige.page.photo.model.PhotoDetail;
import com.aiyige.page.player.PlayerInfo;
import com.aiyige.page.player.PlayerView;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.share.ShareDialog;
import com.aiyige.trace.model.Trace;
import com.aiyige.trace.util.TraceUtil;
import com.aiyige.track.TrackEvent;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.AppCommentUtils;
import com.aiyige.utils.CrmUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.GlideUtil;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.TimeUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.aiyige.utils.widget.CommonDataView;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.vondear.rxtools.RxDeviceTool;
import com.vondear.rxtools.RxKeyboardTool;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.kevin.floatingeditor.EditorCallback;
import cn.kevin.floatingeditor.EditorHolder;
import cn.kevin.floatingeditor.FloatEditorActivity;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@Route(path = ARouterConfig.DetailPage)
public class DetailPage extends BaseActivity implements PlayerView.PlayCallback, View.OnClickListener, CommonDataView.RetrofitStub {

    @BindView(R.id.content)
    View rootView;

    @BindView(R.id.v_loading)
    View vLoading;


    @BindView(R.id.iv_detail_back)
    ImageView ivback;


    @BindView(R.id.fl_media_container)
    FrameLayout playerParentLayout;
    PlayerView playerView;

    @BindView(R.id.rl_input)
    RelativeLayout inputLayout;

    @BindView(R.id.ll_comment_like_favorite)
    LinearLayout hintLayout;

    @BindView(R.id.tv_input)
    TextView inputTextView;

    @BindView(R.id.tv_buy)
    TextView tvBuy;

    @BindView(R.id.tv_send)
    TextView tvSend;

    TextView tvTitle;//标题
    ImageView ivHead;//用户头像
    ImageView ivHeadTemp;//用户头像

    TextView tvUserName;//拥有者用户名
    TextView tvUserNameTemp;//拥有者用户名
    TextView tvVideoInfo;//视频个数时长观看人数
    View userLayout;
    View userLayoutTemp;
    TextView tvHowLong;

    @BindView(R.id.cdv)
    CommonDataView cdv;
    RelativeLayout mRlVideoSelection;// 视频分集父容器控件
    RecyclerView mRecyclerViewSelection;// 视频分集
    RecyclerView mRecyclerViewAbout;// TA的相关
    RecyclerView mRecyclerViewMore;// 更多推荐

    DetailAdapter mAdapter;// 主的RecyclerView，评论列表 适配器
    DetailSelectionAdapter mSelectionAdapter;// 视频分集 适配器
    DetailAboutAdapter mAboutAdapter;// TA的相关 适配器
    DetailMoreAdapter mMoreAdapter;// 更多推荐 适配器

    View safeguardParentView;// 保障的Layout

    View aboutLayout;
    View moreLayout;
    TextView tvCommentTitle;

    TextView tvCommentCount;
    TextView tvLoveCount;

    TextView tvFavoriteCount;

    @BindView(R.id.iv_love)
    ImageView ivPraise;
    @BindView(R.id.iv_collect)
    ImageView ivFavourite;
    @BindView(R.id.iv_comment)
    ImageView ivComment;


    Banner banner;
    View headerView;

    RelativeLayout rlPrice;
    TextView tvPrice;
    TextView tvLineationPrice;

    ImageView ivShare;
    RelativeLayout rlDownload;
    View llim;

    boolean isGoods = true;
    TextView tvDetail;
    TextView tvInfo1;
    TextView tvInfo2;
    LinearLayout llTags;
    LinearLayout safeguardContentLayout;
    RelativeLayout rlAttention;
    RelativeLayout rlAttentionTemp;

    TextView rlAttentionTv;
    TextView rlAttentionTvTemp;
    @Autowired
    public String momentId;
    @Autowired
    public String source = "";
    @Autowired
    public String resourceId = "";

    RequestOptions circleOptions = RequestOptions.circleCropTransform();
    boolean isRequestOkForDetail = false;
    boolean isRequestOkForComment = false;
    private int commentPage = 1;

//    private KeyboardWatcher keyboardWatcher;

    @Autowired
    Moment moment;

    @Autowired
    boolean isMyBuy;

    VideoCourse videoCourse = null;
    DetailBackup detailBackup = null;
    PhotoBackup photoBackup = null;
    MineBackup mineBackup = null;
    StatisticsBackup statisticsBackup = null;
    boolean isRequesting = false;
    RelativeLayout rlBack;
    TrackEvent trackEvent = new TrackEvent();
    String coverUrl;
    View followLayout;
    View followLayoutTemp;
    View followedLayout;
    View followedLayoutTemp;
    View mutualfollowedLayout;
    View mutualfollowedLayoutTemp;
    boolean isReply = false;
    VideoCourseFragment videoCourseFragment;


    RelativeLayout rlSellerHeadLayout;
    RelativeLayout rlSellerHeadLayoutTemp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.page_detail);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        initView();
        setAutoRegisterEventBus(true);
        FloatEditorActivity.setDefaultValue(null);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPaySuccessEventBuss(EventBuySuccess eventBuySuccess) {
        requestData(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPaySuccessEventBuss(EventLogin event) {
        requestData(true);
        cdv.doRefreshRequest();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventAddFollow event) {
        try {
            if (moment.getCreator().equals(event.getBeFollowedId())) {
                moment.getMineBackup().setUserFollowId(event.getFollowId());
                moment.getMineBackup().setMutualFollower(event.isMutualFollow());
                if (event.isMutualFollow()) {
                    showMutualFollowedLayout();
                } else {
                    showFollowedLayout();
                }
                rlAttentionTv.setText(R.string.followed);
                rlAttentionTv.setBackgroundResource(R.drawable.light_green_button_bg);
                rlAttentionTv.setTextColor(ContextCompat.getColor(DetailPage.this, R.color.zwcolor_pink_f93684));

                rlAttentionTvTemp.setText(R.string.followed);
                rlAttentionTvTemp.setBackgroundResource(R.drawable.light_green_button_bg);
                rlAttentionTvTemp.setTextColor(ContextCompat.getColor(DetailPage.this, R.color.zwcolor_pink_f93684));

            }
        } catch (Exception e) {

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventDeleteFollow event) {
        try {
            if (moment.getMineBackup().getUserFollowId().equals(event.getFollowId())) {
                moment.getMineBackup().setUserFollowId("");
                rlAttentionTv.setText(R.string.follow);
                rlAttentionTv.setBackgroundResource(R.drawable.very_light_pink_round_rect);
                rlAttentionTv.setTextColor(ContextCompat.getColor(DetailPage.this, R.color.zwcolor_pink_f93684));

                rlAttentionTvTemp.setText(R.string.follow);
                rlAttentionTvTemp.setBackgroundResource(R.drawable.very_light_pink_round_rect);
                rlAttentionTvTemp.setTextColor(ContextCompat.getColor(DetailPage.this, R.color.zwcolor_pink_f93684));
                showFollowLayout();
            }
        } catch (Exception e) {

        }
    }


    /**
     * 商品发生了变化
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPayChanged(EventMomentChanged event) {
        requestData(true);
    }


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                UIHelper.hideSystemUI(this);
            } else {
                UIHelper.showSystemUI(this);
            }
        }
    }

    /**
     * 核心页面刷新
     */
    private void fillViews() {
        if (moment != null) {
            ivback.setVisibility(View.GONE);// 为了在进入详情页的时候，没有任何数据渲染之前，左上角先出现一个返回按钮让用户可交互返回。
            ivShare.setVisibility(View.VISIBLE);// 在页面数据没有刷新之前，分享按钮隐藏掉
            if (isMySelf()) {
                rlAttention.setVisibility(View.INVISIBLE);
                rlAttentionTemp.setVisibility(View.INVISIBLE);
            } else if (!TextUtils.isEmpty(moment.getMineBackup().getUserFollowId()) && moment.getMineBackup().isMutualFollower()) {
                rlAttentionTv.setText(R.string.followed);
                rlAttentionTvTemp.setText(R.string.followed);
                rlAttention.setVisibility(View.VISIBLE);
                rlAttentionTemp.setVisibility(View.VISIBLE);
                rlAttentionTv.setBackgroundResource(R.drawable.light_green_button_bg);
                rlAttentionTv.setTextColor(ContextCompat.getColor(DetailPage.this, R.color.zwcolor_pink_f93684));
                rlAttentionTvTemp.setBackgroundResource(R.drawable.light_green_button_bg);
                rlAttentionTvTemp.setTextColor(ContextCompat.getColor(DetailPage.this, R.color.zwcolor_pink_f93684));
                showMutualFollowedLayout();
            } else if (!TextUtils.isEmpty(moment.getMineBackup().getUserFollowId())) {
                rlAttentionTv.setText(R.string.followed);
                rlAttentionTvTemp.setText(R.string.followed);
                rlAttention.setVisibility(View.VISIBLE);
                rlAttentionTemp.setVisibility(View.VISIBLE);
                rlAttentionTv.setBackgroundResource(R.drawable.light_green_button_bg);
                rlAttentionTv.setTextColor(ContextCompat.getColor(DetailPage.this, R.color.zwcolor_pink_f93684));
                rlAttentionTvTemp.setBackgroundResource(R.drawable.light_green_button_bg);
                rlAttentionTvTemp.setTextColor(ContextCompat.getColor(DetailPage.this, R.color.zwcolor_pink_f93684));
                showFollowedLayout();
            } else {
                rlAttentionTvTemp.setText(R.string.follow);
                rlAttentionTv.setText(R.string.follow);
                rlAttention.setVisibility(View.VISIBLE);
                rlAttentionTemp.setVisibility(View.VISIBLE);
                rlAttentionTv.setBackgroundResource(R.drawable.button_bg);
                rlAttentionTv.setTextColor(ContextCompat.getColor(DetailPage.this, R.color.white));
                rlAttentionTvTemp.setBackgroundResource(R.drawable.button_bg);
                rlAttentionTvTemp.setTextColor(ContextCompat.getColor(DetailPage.this, R.color.white));
                showFollowLayout();
            }
            mAdapter.setMoment(moment);
            tvHowLong.setText(TimeUtils.getStandardDate((moment.getOnsellTime()) + ""));
            tvTitle.setText(moment.getTitle());

            // 创建者信息
            CreatorBackup creatorBackup = moment.getCreatorBackup();
            if (moment.getCreatorBackup() != null) {
                GlideUtil.with(this).small().loadAvatar(creatorBackup.getAvatar()).into(ivHead);
                GlideUtil.with(this).small().loadAvatar(creatorBackup.getAvatar()).into(ivHeadTemp);
                tvUserName.setText(creatorBackup.getName());
                tvUserNameTemp.setText(creatorBackup.getName());
            }

            long watchCount = 0;
            long sellCount = 0;
            statisticsBackup = moment.getStatisticsBackup();
            if (statisticsBackup != null) {
                watchCount = statisticsBackup.getViewCount();
                sellCount = statisticsBackup.getSellCount();
            }

            mineBackup = moment.getMineBackup();
            // 上次播放进度// 当前需求只记录和显示最后一次播放的那一集
            PlayProgressModel playProgressModel = ListUtil.isEmpty(moment.getStudyProgressBackup()) ? null : moment.getStudyProgressBackup().get(0);
            if (mineBackup != null) {
//                mineBackup.setBuyed((!isNull(moment.getSubject()) && !moment.getSubject().equals(Moment.SUBJECT_VIDEO_COURSE)) ? 1 : 0);
                ivFavourite.setSelected(mineBackup.isFavorited());
                tvFavoriteCount.setSelected(mineBackup.isFavorited());
                ivPraise.setSelected(mineBackup.isPraised());
                tvLoveCount.setSelected(mineBackup.isPraised());
            }

            // 因为属性雷同，普通视频 & 教学视频 共用一个VideoCourse
            int videoCount = 0;
            if (moment.getMoreBackup() != null && (moment.getSubject().equals(Subject.video) || moment.getSubject().equals(Subject.video_course))) {
                videoCourse = JsonUtil.toObject(moment.getMoreBackup(), VideoCourse.class);
                videoCount = videoCourse.getVideoCount();
            }

            detailBackup = moment.getDetailBackup();
            if (detailBackup != null) {
                mSelectionAdapter.setSubject(moment.getSubject());
            }

            if (moment.getSubject().equals(Subject.video)) {
                //temp
                rlSellerHeadLayout.setVisibility(View.GONE);
                rlSellerHeadLayoutTemp.setVisibility(View.VISIBLE);
                // 普通视频 全免费
                if (playerView == null) {
                    playerView = (PlayerView) findViewById(R.id.player);
                    playerView.setPlayerParentView(playerParentLayout);
                }
                tvHowLong.setVisibility(View.GONE);
//                tvVideoInfo.setText(getResources().getString(R.string.free_video_info, videoCount + "", getVideoDuration(), watchCount + ""));
                tvVideoInfo.setText(getResources().getString(R.string.watch_num, watchCount + "") + " / " + TimeUtils.getStandardDate((moment.getOnsellTime()) + ""));
                tvDetail.setVisibility(TextUtils.isEmpty(moment.getSummary()) ? View.GONE : View.VISIBLE);
                tvDetail.setText(moment.getSummary());
                rlPrice.setVisibility(View.GONE);

                llTags.setVisibility(View.GONE);
                if (playerView.isPlaying()) {
                    playChange(playerView.getPlayIndex());
                }
                if (!ListUtil.isEmpty(videoCourse.getVideos())) {
                    coverUrl = videoCourse.getVideos().get(0).getCover();
                    if (videoCourse.getVideos().size() <= 1) {
                        mRlVideoSelection.setVisibility(View.GONE);
                    } else {
                        mSelectionAdapter.setNewData(videoCourse.getVideos());
                    }
                    playerView.setPlayCallback(this);
                    if (playProgressModel != null) {
                        playerView.start(videoEntity2PlayerInfo(videoCourse.getVideos()), playProgressModel.getStage() - 1, playProgressModel.getProgress());
                    } else {
                        playerView.start(videoEntity2PlayerInfo(videoCourse.getVideos()), 0);
                    }
                } else {
                    mRlVideoSelection.setVisibility(View.GONE);// 当只有一个视频的时候，隐藏视频选择控件
                }
//                rlBack.setVisibility(View.GONE);
                tvBuy.setVisibility(View.GONE);
                llim.setVisibility(View.GONE);
            } else if (moment.getSubject().equals(Subject.video_course)) {
                //temp
                rlSellerHeadLayout.setVisibility(View.VISIBLE);
                rlSellerHeadLayoutTemp.setVisibility(View.GONE);
                // 教学视频 收费
//                rlBack.setVisibility(View.GONE);
                if (playerView == null) {
                    playerView = (PlayerView) findViewById(R.id.player);
                    playerView.setPlayerParentView(playerParentLayout);
                }
                tvVideoInfo.setText(getResources().getString(R.string.nofree_video_info, sellCount + "", watchCount + ""));
                rlPrice.setVisibility(isMyBuy ? View.GONE : View.VISIBLE);
                tvDetail.setVisibility(View.GONE);
                if (isMySelf() || isBuyed()) {
                    tvBuy.setVisibility(View.GONE);
                } else {
                    tvBuy.setVisibility(View.VISIBLE);
                }
                llTags.setVisibility(View.VISIBLE);
                convertVideo(videoCourse.getVideos());//把免费的视频遍历一下 放在最前面
                if (playerView.isPlaying()) {
                    playChange(playerView.getPlayIndex());
                }
                if (!ListUtil.isEmpty(videoCourse.getVideos())) {
//                    if (videoCourse.getVideos().size() <= 1) {
//                        mRlVideoSelection.setVisibility(View.GONE);
//                    } else {
//                        mSelectionAdapter.setNewData(videoCourse.getVideos());
//                    }
                    coverUrl = videoCourse.getVideos().get(0).getCover();
                    mSelectionAdapter.setNewData(videoCourse.getVideos());
                    playerView.setPlayCallback(this);
                    if (playProgressModel != null) {
                        playerView.start(videoEntity2PlayerInfo(videoCourse.getVideos()), playProgressModel.getStage() - 1, playProgressModel.getProgress());
                    } else {
                        playerView.start(videoEntity2PlayerInfo(videoCourse.getVideos()), 0);
                    }
                }
//                else {
//                    mRlVideoSelection.setVisibility(View.GONE);
//                }
                llim.setVisibility(isMySelf() ? View.GONE : View.VISIBLE);
            } else if (moment.getSubject().equals(Subject.photo)) {
                //temp
                rlSellerHeadLayout.setVisibility(View.GONE);
                rlSellerHeadLayoutTemp.setVisibility(View.VISIBLE);
                RxDeviceTool.setPortrait(this);
                tvVideoInfo.setText(getResources().getString(R.string.watch_num, watchCount + "") + "/" + TimeUtils.getStandardDate((moment.getOnsellTime()) + ""));
                rlPrice.setVisibility(View.GONE);
                tvDetail.setVisibility(View.GONE);
                llTags.setVisibility(View.GONE);
                tvBuy.setVisibility(View.GONE);
                rlDownload.setVisibility(View.INVISIBLE);
                // 图集do
//                playerParentLayout.removeAllViews();
//                ((RelativeLayout) findViewById(R.id.rl_player)).removeAllViews();
                banner = (Banner) findViewById(R.id.banner);
                banner.setVisibility(View.VISIBLE);
                llim.setVisibility(View.GONE);
                tvHowLong.setVisibility(View.GONE);
                initBanner();
            } else {
                finish();
            }
            if (videoCourseFragment != null) {
                videoCourseFragment.setMoment(moment);
            }
            // 保障的数据为空，则不显示
            safeguardParentView.setVisibility(detailBackup == null || ListUtil.isEmpty(detailBackup.getGuarantee()) ? View.GONE : View.VISIBLE);
//            tvInfo1.setText(getString(R.string.the_type_of_course) + (videoCourse == null ? "" : videoCourse.getCourseType()));
//            tvInfo2.setText(getString(R.string.interests) + getInterestStr(moment.getTags()));
            if (videoCourse != null && !ListUtil.isEmpty(detailBackup.getGuarantee())) {
                if (safeguardContentLayout.getChildCount() == 0) {
                    int max = 0;
                    for (Guarantee entity : detailBackup.getGuarantee()) {
                        if (entity == null) continue;
                        max++;
                        if (max > 4) {// 详情页外面，最多展示4个
                            break;
                        }
                        LinearLayout view = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_safeguard_tag, null);
                        TextView title = (TextView) view.findViewById(R.id.tv_tag1);
                        title.setText(entity.getName());
                        view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT));
                        safeguardContentLayout.addView(view);
                    }
                }
            }
            // TA的相关
            boolean aboutDataEmpty = ListUtil.isEmpty(moment.getRecommendMineBackup());
            aboutLayout.setVisibility(aboutDataEmpty ? View.GONE : View.VISIBLE);
            mAboutAdapter.setNewData(moment.getRecommendMineBackup());
            // 更多推荐
            boolean moreDataEmpty = ListUtil.isEmpty(moment.getRecommendOtherBackup());
            moreLayout.setVisibility(moreDataEmpty ? View.GONE : View.VISIBLE);
            mMoreAdapter.setNewData(moment.getRecommendOtherBackup());
            long commentCount = statisticsBackup != null ? statisticsBackup.getCommentCount() : 0;
            tvCommentTitle.setText(getResources().getString(R.string.comment_count, commentCount + ""));
            tvCommentCount.setText(getCountValue(commentCount));
            long praiseCount = statisticsBackup != null ? statisticsBackup.getPraiseCount() : 0;
            tvLoveCount.setText(getCountValue(praiseCount));
            if (mineBackup != null) {
                tvLoveCount.setSelected(mineBackup.isPraised());
            }
            long favoriteCount = statisticsBackup != null ? statisticsBackup.getFavoriteCount() : 0;
            tvFavoriteCount.setText(getCountValue(favoriteCount));
            CommodityBackup commodityBackup = moment.getCommodityBackup();
            if (commodityBackup != null) {
                // 如果getOnSalesBackup不为空，那么这里的price表示是现在的价格，而原来的price就是划线价
                if (moment.getOnSalesBackup() != null && moment.getOnSalesBackup().getPrice() != null) {
                    tvLineationPrice.setText("￥" + StringUtils.priceFormat(commodityBackup.getPrice()));
                    tvPrice.setText(StringUtils.priceFormat(moment.getOnSalesBackup().getPrice()));
                } else {
                    tvLineationPrice.setText("");
                    tvPrice.setText(StringUtils.priceFormat(commodityBackup.getPrice()));
                }
            }
        } else {
            ToastX.show(getString(R.string.page_empty));
            finish();
        }

    }

    public void initBanner() {
        if (moment == null || moment.getMoreBackup() == null) {
            return;
        }
        if (banner != null) {
            banner.releaseBanner();
        }
        photoBackup = JsonUtil.toObject(moment.getMoreBackup(), PhotoBackup.class);
        if (photoBackup == null || ListUtil.isEmpty(photoBackup.getPhotos())) {
            return;
        }
        coverUrl = photoBackup.getPhotos().get(0).getUrl();
        banner.setImages(photoBackup.getPhotos());
        banner.setBannerTitles(getBannerTitles(photoBackup.getPhotos()));
        banner.setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE);
        banner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                GlideUtil.with(context).asGif().big().loadCover(((SinglePhoto) path).getUrl()).into(imageView);
            }
        });
        banner.setBannerAnimation(Transformer.Default);
        banner.setDelayTime(3000);
        banner.isAutoPlay(true);
        banner.setIndicatorGravity(BannerConfig.RIGHT);
        banner.start();
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                startPhotoPage(position);
            }
        });
    }

    private List<String> getBannerTitles(List<SinglePhoto> singlePhotoList) {
        if (singlePhotoList == null) {
            return null;
        }
        List<String> list = new ArrayList<>();
        for (SinglePhoto imageEntity : singlePhotoList) {
            list.add(imageEntity.getTitle());
        }
        return list;
    }

    private boolean isMySelf() {
        if (moment != null && !isNull(moment.getCreator())) {
            String userId = AccountUtil.getCurrentUser() != null ? AccountUtil.getCurrentUser().getId() : "";
            if (userId.equals(moment.getCreator())) {
                return true;
            }
        }
        return false;
    }


    private void startPhotoPage(int position) {
        if (photoBackup == null) {
            return;
        }
        List<Photo> photoList = new LinkedList<>();
        for (SinglePhoto imageEntity : photoBackup.getPhotos()) {
            photoList.add(Photo.newBuilder()
                    .url(imageEntity.getUrl())
                    .introduction(imageEntity.getTitle())
                    .build());
        }
        PhotoDetail photoDetail = PhotoDetail.newBuilder()
                .goodsId(moment.getId())
                .localPhoto(false)
                .photoList(photoList)
                .title(moment.getTitle())
                .playIndex(position)
                .build();
        ARouter.getInstance()
                .build(ARouterConfig.PhotoPage)
                .withParcelable("photoDetail", photoDetail)
                .navigation();
    }

    private void initView() {
        mAdapter = new DetailAdapter();
        mAdapter.setEnableLoadMore(true);
        mAdapter.setHeaderFooterEmpty(true, false);
        headerView = getLayoutInflater().inflate(R.layout.detail_header, null);
        headerView.setVisibility(View.INVISIBLE);// 先隐藏，等所有接口都ok再显示出来
        mAdapter.addHeaderView(headerView);
        tvHowLong = (TextView) headerView.findViewById(R.id.tv_how_long);
        llim = headerView.findViewById(R.id.ll_im);
        tvInfo1 = (TextView) headerView.findViewById(R.id.tv_info_1);
        tvInfo2 = (TextView) headerView.findViewById(R.id.tv_info_2);
        tvDetail = (TextView) headerView.findViewById(R.id.tv_detail);
        llTags = (LinearLayout) headerView.findViewById(R.id.ll_tags);
        safeguardContentLayout = (LinearLayout) headerView.findViewById(R.id.ll_safeguard);
        rlAttention = (RelativeLayout) headerView.findViewById(R.id.rl_attention);
        rlAttentionTemp = (RelativeLayout) headerView.findViewById(R.id.rl_attention_temp);

        followLayout = headerView.findViewById(R.id.followLayout);
        followLayoutTemp = headerView.findViewById(R.id.followLayout_temp);
        followedLayout = headerView.findViewById(R.id.followedLayout);
        followedLayoutTemp = headerView.findViewById(R.id.followedLayout_temp);
        mutualfollowedLayout = headerView.findViewById(R.id.mutualfollowedLayout);
        mutualfollowedLayoutTemp = headerView.findViewById(R.id.mutualfollowedLayout_temp);
        rlAttentionTv = (TextView) headerView.findViewById(R.id.rl_attentionTv);
        rlAttentionTvTemp = (TextView) headerView.findViewById(R.id.rl_attentionTv_temp);
        rlAttention.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!AccountUtil.isLogin()) {
                    ARouter.getInstance()
                            .build(ARouterConfig.LoginPage)
                            .navigation(DetailPage.this);
                } else if (moment != null) {
                    if (TextUtils.isEmpty(moment.getMineBackup().getUserFollowId())) {
                        new AddFollowTask().execute();
                    } else {
                        new DeleteFollowTask().execute();
                    }
                }
            }
        });
        rlAttentionTemp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!AccountUtil.isLogin()) {
                    ARouter.getInstance()
                            .build(ARouterConfig.LoginPage)
                            .navigation(DetailPage.this);
                } else if (moment != null) {
                    if (TextUtils.isEmpty(moment.getMineBackup().getUserFollowId())) {
                        new AddFollowTask().execute();
                    } else {
                        new DeleteFollowTask().execute();
                    }
                }
            }
        });
        ivShare = (ImageView) findViewById(R.id.iv_share);
        ivShare.setOnClickListener(this);
        rlDownload = (RelativeLayout) headerView.findViewById(R.id.rl_download);
        rlDownload.setOnClickListener(this);
        rlPrice = (RelativeLayout) headerView.findViewById(R.id.rl_price);
        tvPrice = (TextView) headerView.findViewById(R.id.tv_price);
        tvLineationPrice = (TextView) headerView.findViewById(R.id.tv_lineation_price);

        tvCommentTitle = (TextView) headerView.findViewById(R.id.tv_comment_count);
        tvCommentCount = (TextView) findViewById(R.id.tv_comment_count);
        tvLoveCount = (TextView) findViewById(R.id.tv_love_count);
        tvFavoriteCount = (TextView) findViewById(R.id.tv_collect_count);
        tvTitle = (TextView) headerView.findViewById(R.id.tv_title);
        ivHead = (ImageView) headerView.findViewById(R.id.iv_head);
        ivHeadTemp = (ImageView) headerView.findViewById(R.id.iv_head_temp);
        tvUserName = (TextView) headerView.findViewById(R.id.tv_username);
        tvUserNameTemp = (TextView) headerView.findViewById(R.id.tv_username_temp);
        tvVideoInfo = (TextView) headerView.findViewById(R.id.tv_video_info);
        userLayout = headerView.findViewById(R.id.rl_user);

        userLayoutTemp = headerView.findViewById(R.id.rl_user_temp);

        rlSellerHeadLayout = headerView.findViewById(R.id.rl_seller_head_layout);
        rlSellerHeadLayoutTemp = headerView.findViewById(R.id.rl_seller_head_layout_temp);

        tvLineationPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
        ivComment.setOnClickListener(this);
        if (isGoods) {
//            View videoInfoView = headerView.findViewById(R.id.rl_people_info);
//            videoInfoView.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    if (moment == null || ListUtil.isEmpty(moment.getTags())) {
//                        return;
//                    }
//                    VideoCourseFragment.showAsDropDown(DetailPage.this, moment, playerParentLayout);
//                }
//            });
//            Fragment fragment = headerView.findViewById(R.id.fm_video_course);

            if (videoCourseFragment == null) {
                videoCourseFragment = (VideoCourseFragment) getSupportFragmentManager().findFragmentById(R.id.fm_video_course);
//                VideoCourseFragment rightFragment;
//                rightFragment = (VideoCourseFragment) getFragmentManager().findFragmentById(R.id.fm_video_course);


//                videoCourseFragment = new VideoCourseFragment();
//                android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
//                android.support.v4.app.FragmentTransaction fragmentTransaction = fm.beginTransaction();
//                fragmentTransaction.replace(R.id.fm_video_course, videoCourseFragment);
//                fragmentTransaction.commit();

//                videoCourseFragment=new VideoCourseFragment();

                //动态添加到布局中，注意replace中的第一个参数为activity_main中的id

//                getSupportFragmentManager().beginTransaction().replace(R.id.container,videoCourseFragment).commit();
            }
//            videoCourseFragment.setMoment(moment);

            safeguardParentView = headerView.findViewById(R.id.rl_safeguard_info);
            safeguardParentView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (detailBackup == null || ListUtil.isEmpty(detailBackup.getGuarantee())) {
                        return;
                    }
                    DialogSafeguard.showAsDropDown(DetailPage.this, detailBackup.getGuarantee(), playerParentLayout);
                }
            });
        }
//        inputTextView.setFilters(new InputFilter[]{new InputNumFilter(200, true)});
//        // 评论输入
//        inputTextView.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                if (inputTextView.getText().length() > 0) {
//                    hintBuyLayout();
//                } else if (inputTextView.getText().length() == 0) {
//                    visibleBuyLayout();
//                }
//            }
//        });
//        inputTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                if (hasFocus && !LoginManager.isLogin()) {
//                    LoginManager.getInstance().isLogin(true);
//                    inputTextView.clearFocus();
//                }
//            }
//        });

        // 键盘显示隐藏监听
//        AppUtils.addOnSoftKeyBoardVisibleListener(this, new AppUtils.SoftKeyBoardCallback() {
//            @Override
//            public void show() {
//                hintBuyLayout();
//            }
//
//            @Override
//            public void hide() {
//                inputTextView.setHint(getString(R.string.text_input_comment_hint));
//                visibleBuyLayout();
//            }
//        });
        // 评论列表事件
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (!LoginManager.getInstance().isLogin(true)) {
                    return;
                }
//                Comment commentEntity = mAdapter.getItem(position);
//                Comment.CreatorBackup creatorBackup = commentEntity.getCreatorBackup();
//                inputTextView.setHint("回复：" + creatorBackup.getName());
//                //让编辑框弹出来，并显示对谁进行评论
//                inputTextView.setFocusable(true);
//                inputTextView.setFocusableInTouchMode(true);
//                inputTextView.requestFocus();
//                inputTextView.setTag(commentEntity);
//                //打开软键盘
//                if (getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE) {
////                Toast.makeText(getActivity(), "显示", Toast.LENGTH_SHORT).show();
//                    Log.i("xiatest", "显示了");
//                } else {
//                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
//                    Log.i("xiatest", "没有显示");
//                }
                Comment commentEntity = mAdapter.getItem(position);
                Comment.CreatorBackup creatorBackup = commentEntity.getCreatorBackup();
                String hintString = "回复：" + creatorBackup.getName();
                comment(hintString, commentEntity);
            }
        });
//        keyboardWatcher = KeyboardWatcher.get().init(this, getWindow().getDecorView(), new OnKeyboardStateChangeListener() {
//            @Override
//            public void onKeyboardStateChange(boolean isShow, int heightDifference) {
//                if (isShow) {
////                    Toast.makeText(getApplication(), "键盘显示了！高度差：" + heightDifference, Toast.LENGTH_SHORT).show();
//                } else {
//                    inputTextView.setHint(getString(R.string.text_input_comment_hint));
//                    inputTextView.setTag(null);
//                }
//            }
//        });

        userLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (moment != null && moment.getCreatorBackup() != null) {
                    ARouter.getInstance().build(ARouterConfig.UserPage)
                            .withString("userId", moment.getCreatorBackup().getId())
                            .navigation();
                }
            }
        });
        userLayoutTemp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (moment != null && moment.getCreatorBackup() != null) {
                    ARouter.getInstance().build(ARouterConfig.UserPage)
                            .withString("userId", moment.getCreatorBackup().getId())
                            .navigation();
                }
            }
        });
        llim.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (moment != null && Moment.SUBJECT_VIDEO_COURSE.equals(moment.getSubject())) {
                    CrmUtil.createCustomer(moment.getCreator());
                }

                if (!TextUtils.isEmpty(getSellerAccid())) {
//                    DialUtil.dial(videoCourse.getServicePhone());
                    showContactSellerImOrServiceIm();
                } else {
                    if (!LoginManager.getInstance().isLogin())
                        LoginManager.getInstance().startLoginActivity();
                }
            }
        });
        initSelection();
        initAbout();
        initMore();
        requestData(false);
        cdv.config(mAdapter, DetailPage.this);

        cdv.doRefreshRequest();
        cdv.setErrorHandler(new CommonDataView.ErrorHandler() {
            @Override
            public void onResponseError(String errorMsg) {
                if (moment == null && !isRequesting) {
                    requestData(false);
                }
            }

            @Override
            public void onNetError(String errorMsg) {
                if (moment == null && !isRequesting) {
                    requestData(false);
                }
            }
        });
        rlBack = (RelativeLayout) findViewById(R.id.rl_back);
        rlBack.setVisibility(View.VISIBLE);
        rlBack.setOnClickListener(this);
        ivback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        inputTextView.setOnClickListener(this);
    }


    private void showContactSellerImOrServiceIm() {
        List<KeyValue> list = new ArrayList<>();
        list.add(new KeyValue(0,getString(R.string.contact_seller)));
        list.add(new KeyValue(1,getString(R.string.contact_platform_for_customer_service)));
        final CommonOperationDialog dialog = new CommonOperationDialog();
        dialog.setData(list);
        dialog.setLisenter(new CommonOperationDialog.Listener() {
            @Override
            public void onSelect(int position) {
                if (position == 0) {
                    if (!TextUtils.isEmpty(getSellerAccid())) {
                        SessionHelper.startP2PSession(DetailPage.this, getSellerAccid());
                    }
                } else if (position == 1) {
                    SessionHelper.getInstance().imService(DetailPage.this);
//                    String accid = ListUtil.isEmpty(LoginManager.getInstance().getServiceList())?null:LoginManager.getInstance().getServiceList().get(0).getAccid();
//                    if (!TextUtils.isEmpty(accid)) {
//                        SessionHelper.startP2PSession(DetailPage.this, accid);
//                    } else {
//                        // 如果系统启动没有取到，则临时取
//                        Handler handler = new Handler(){
//                            @Override
//                            public void handleMessage(Message msg) {
//                                hideLoading();
//                                String accid = ListUtil.isEmpty(LoginManager.getInstance().getServiceList())?null:LoginManager.getInstance().getServiceList().get(0).getAccid();
//                                if (!TextUtils.isEmpty(accid)) {
//                                    SessionHelper.startP2PSession(DetailPage.this, accid);
//                                }
//                            }
//                        };
//                        showLoading();
//                        LoginManager.getInstance().getServiceACCIDList(handler);
//                    }
                }
            }
        });
        dialog.show(getSupportFragmentManager(), null);
    }

    private void hintBuyLayout() {
        hintLayout.setVisibility(View.GONE);
        tvBuy.setVisibility(View.GONE);
        tvSend.setVisibility(View.VISIBLE);
    }

    private void visibleBuyLayout() {
        hintLayout.setVisibility(View.VISIBLE);
        if (moment != null && moment.getSubject().equals(Subject.video_course) && !isMySelf()) {
            tvBuy.setVisibility(View.VISIBLE);
            if (isBuyed()) {
                tvBuy.setVisibility(View.GONE);
            }
        }
        tvSend.setVisibility(View.GONE);
    }

    private void comment(final String hintString, final Comment comment) {
        if (!LoginManager.isLogin()) {
            LoginPage.start();
            LoginManager.getInstance().addLoginCallBack(new ILoginCallBack() {
                @Override
                public void success(User userInfo) {
                    comment(hintString, comment);
                }

                @Override
                public void error(String errorCode) {

                }
            });
            return;
        }
//        if (FloatEditorActivity.getObject() != null) {
//            Comment lastComment = (Comment)FloatEditorActivity.getObject();
//            if (comment != null && !TextUtils.isEmpty(comment.getId()) && lastComment != null && !TextUtils.isEmpty(lastComment.getId())
//                    && comment.getId().endsWith(lastComment.getId())) {
//                defaultValue = lastComment.getUnSubmitContent();// 找到上次未完成的编辑内容
//            }
//        }
//        FloatEditorActivity.setObject(comment);// 记录被评论的对象

        FloatEditorActivity.openEditor(DetailPage.this, new EditorCallback() {
                    @Override
                    public void onCancel(String content) {
                        FloatEditorActivity.setDefaultValue(content);
                        RxKeyboardTool.hideSoftInput(DetailPage.this);
                    }

                    @Override
                    public void onSubmit(String content) {
                        FloatEditorActivity.setDefaultValue(null);
                        doComment(comment, content);
                    }

                    @Override
                    public void onAttached(ViewGroup rootView) {


                    }
                },
                new EditorHolder(R.layout.fast_reply_floating_layout,
                        R.id.tv_cancel, R.id.tv_submit, R.id.et_content), hintString, new InputFilter[]{new InputNumFilter(200, true)});
    }

    private boolean isBuyed() {
        if (mineBackup != null) {
            return mineBackup.isBuyed();
        } else {
            return false;
        }
    }

    private void initSelection() {
        if (mRecyclerViewSelection == null) {
            mRecyclerViewSelection = (RecyclerView) headerView.findViewById(R.id.rv_video_selections);
            mRlVideoSelection = (RelativeLayout) headerView.findViewById(R.id.rl_video_selections);

            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
            linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            mRecyclerViewSelection.setLayoutManager(linearLayoutManager);
            mRecyclerViewSelection.addItemDecoration(new ItemRecyclerViewDivider(UIHelper.dip2px(this, 3.5f), 0, UIHelper.dip2px(this, 3.5f), 0));
            mSelectionAdapter = new DetailSelectionAdapter();

            mRecyclerViewSelection.setAdapter(mSelectionAdapter);
            mSelectionAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    for (int i = 0; i < adapter.getData().size(); i++) {
                        ((SingleVideo) adapter.getData().get(i)).setSelected(position == i);
                    }
                    mSelectionAdapter.notifyDataSetChanged();
                    playerView.setStopLoopPlayback(true);//停止自动播放
                    playerView.play(position);
                }
            });
        }


    }


    private void initAbout() {
        aboutLayout = headerView.findViewById(R.id.ll_about);
        mRecyclerViewAbout = (RecyclerView) headerView.findViewById(R.id.rv_about);
        GridLayoutManager linearLayoutManager = new GridLayoutManager(this, 2);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerViewAbout.setLayoutManager(linearLayoutManager);
        mAboutAdapter = new DetailAboutAdapter();
        mRecyclerViewAbout.setAdapter(mAboutAdapter);
        mAboutAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Moment moment = (Moment) adapter.getData().get(position);
                if (moment != null && !isNull(moment.getRouter())) {
                    Router.start(moment.getRouter());
                }

            }
        });
    }

    private void initMore() {
        moreLayout = headerView.findViewById(R.id.ll_more);
        mRecyclerViewMore = (RecyclerView) headerView.findViewById(R.id.rv_more);
        GridLayoutManager linearLayoutManager = new GridLayoutManager(this, 2);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerViewMore.setLayoutManager(linearLayoutManager);
        mMoreAdapter = new DetailMoreAdapter();
        mRecyclerViewMore.setAdapter(mMoreAdapter);
        mMoreAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Moment moment = (Moment) adapter.getData().get(position);
                if (moment != null && !isNull(moment.getRouter())) {
                    Router.start(moment.getRouter());
                }
            }
        });
    }


    @Override
    protected void onResume() {
        AppCommentUtils.getInstance().showAppCommentDialog(this);
        super.onResume();
    }


    private String getCountValue(long count) {
        if (count <= 0) {
            return "0";
        } else {
            return String.valueOf(count);
        }
    }

    private List<PlayerInfo> videoEntity2PlayerInfo(List<SingleVideo> list) {
        if (list == null || list.isEmpty()) {
            return null;
        }
        List<PlayerInfo> playList = new ArrayList<>();
        for (SingleVideo videoEntity : list) {
            playList.add(new PlayerInfo(videoEntity.getUrl(), videoEntity.getTitle(), videoEntity.getCover(), (mineBackup.isBuyed() || videoEntity.isFree())));
        }
        return playList;
    }

    public void requestData(boolean buyRefresh) {
        if (!buyRefresh && moment != null) {
            fillViews();
            return;
        }
        if (isNull(momentId)) {
            return;
        }
//        showLoading();
        isRequesting = true;
        Trace trace = TraceUtil.peek();
        String tid = "";
        int code = 0;
        if (trace != null) {
            tid = trace.getTraceId();
            code = trace.getCode();
        }
        ApiManager.getService().getMoment(momentId, source, resourceId, tid, code).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                isRequesting = false;
                isRequestOkForDetail = true;
                if (isRequestOkForComment) {
                    hideLoading();
                    headerView.setVisibility(View.VISIBLE);
                    playerParentLayout.setVisibility(View.VISIBLE);
                    inputLayout.setVisibility(View.VISIBLE);
                    cdv.setVisibility(View.VISIBLE);
                    vLoading.setVisibility(View.GONE);
                }
                try {
                    if (response.code() == ResponseCode.OK) {
                        String json = RetrofitUtil.getResponseBodyAsString(response);
                        moment = new Moment(JsonUtil.toObject(json, Moment.class));
                        fillViews();
                    } else if (response.code() == ResponseCode.NOT_FOUND) {
                        throw new Exception(StringUtils.getString(R.string.content_not_found));
                    } else {
                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                    }
                } catch (Exception e) {
                    isRequesting = false;
                    isRequestOkForDetail = true;
                    if (isRequestOkForComment) {
                        hideLoading();
                    }
                    ToastX.show(e);
                    finish();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                isRequesting = false;
                isRequestOkForDetail = true;
                if (isRequestOkForComment) {
                    hideLoading();
                }
                if (!TextUtils.isEmpty(t.getMessage())) {
                    ToastX.show(t.getMessage());
                }
                finish();
            }
        });
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        boolean landscape = newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE;
        orientation(landscape);
    }


    @Override
    public void onBackPressed() {
        if (playerView != null) {
            if (!playerView.isLandspace()) {
                super.onBackPressed();
            } else {
                playerView.onBackPressed();
            }
        } else {
            super.onBackPressed();
        }
    }

    @OnClick({R.id.rl_praise, R.id.rl_collect, R.id.tv_send, R.id.tv_buy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_praise:
                doPraise();
                break;
            case R.id.rl_collect:
                doFavorite();
                break;
//            case R.id.tv_send:
//                doComment();
//                break;
            case R.id.tv_buy:
                doBuy();
                break;
        }
    }


    private void doComment(Comment originalComment, String commentContent) {
        if (!LoginManager.isLogin()) {
            LoginPage.start();
            return;
        }
        if (moment == null) {
            return;
        }
//        final String commentContent = inputTextView.getText().toString().trim();
        if (isEmpty(commentContent)) {
            ToastX.show(getString(R.string.comment_cannot_empty));
            return;
        }
        commentContent = commentContent.replace("\n", "");
        commentContent = commentContent.replace("\t", "");
        Comment comment = new Comment();
        comment.setSubject(moment.getSubject());
        comment.setContent(commentContent);
        comment.setOriginObjectId(moment.getId());


        if (originalComment != null) {
            isReply = true;// 回复留言
            comment.setObjectId(originalComment.getId());// 原留言的"留言ID"commentId
            comment.setObjectType(Comment.comment);// 类型是comment 表示回复
        } else {
            comment.setObjectId(moment.getId());// momentId
            comment.setObjectType(Comment.moment);// 类型是moment 表示留言
        }
        final AddCommentRequest.Builder builder = AddCommentRequest.newBuilder().comment(comment);
        builder.build().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                hideLoading();
                String json = null;
                try {
                    if (response.isSuccessful()) {
                        json = response.body().string();
                        Comment baseResponse = JSON.parseObject(json, Comment.class);
                        if (baseResponse != null) {
                            mAdapter.addData(0, baseResponse);
//                            inputTextView.setText("");
//                            inputTextView.setHint(getString(R.string.text_input_comment_hint));
                            if (statisticsBackup != null) {
                                statisticsBackup.setCommentCount(statisticsBackup.getCommentCount() + 1);
                                tvCommentCount.setText(getCountValue(statisticsBackup.getCommentCount()));
                                tvCommentTitle.setText(getResources().getString(R.string.comment_count, statisticsBackup.getCommentCount() + ""));
                            }
                            ToastX.show(getString(isReply ? R.string.reply_comment_success : R.string.comment_success));
                        }
                    } else {
                        ToastX.show(ErrorUtil.extractMessageFromErrorResponse(response));
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                hideLoading();
                if (t != null && !TextUtils.isEmpty(t.getMessage())) {
                    ToastX.show(t.getMessage());
                }
            }
        });
        showLoading();

    }

    boolean isRequestPraise = false;

    private void doPraise() {
        if (!LoginManager.isLogin()) {
            LoginPage.start();
            return;
        }
        if (moment == null || mineBackup == null) {
            return;
        }
        boolean isPraised = mineBackup.isPraised();
        if (isRequestPraise) {
            return;
        }
        isRequestPraise = true;
        if (!isPraised) {
            Praise praise = Praise.newBuilder().objectId(moment.getId()).objectType("moment").subject(moment.getSubject()).build();
            (new PraiseRequest()).addPraises(praise).enqueue(new Callback<ResponseBody>() {

                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    isRequestPraise = false;
                    if (response.isSuccessful()) {
                        try {
                            String json = response.body().string();
                            Praise parseObject = JSON.parseObject(json, Praise.class);
                            if (parseObject != null && !isNull(parseObject.getId())) {
                                mineBackup.setPraiseId(parseObject.getId());
                                ivPraise.setSelected(mineBackup.isPraised());
                                statisticsBackup.setPraiseCount(statisticsBackup.getPraiseCount() + 1);
                                tvLoveCount.setText(getCountValue(statisticsBackup.getPraiseCount()));
                                tvLoveCount.setSelected(mineBackup.isPraised());
                            }
                        } catch (Exception e) {
                            onFailure(call, e);
                        }
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    isRequestPraise = false;
                }
            });
        } else {
            (new PraiseRequest()).deletePraises(mineBackup.getPraiseId()).enqueue(new Callback<ResponseBody>() {

                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    isRequestPraise = false;
                    if (response.isSuccessful()) {
                        statisticsBackup.setPraiseCount(statisticsBackup.getPraiseCount() - 1);
                        mineBackup.setPraiseId(null);
                        ivPraise.setSelected(mineBackup.isPraised());
                        tvLoveCount.setText(getCountValue(statisticsBackup.getPraiseCount()));
                        tvLoveCount.setSelected(mineBackup.isPraised());
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    isRequestPraise = false;
                    if (t != null && !TextUtils.isEmpty(t.getMessage())) {
                        ToastX.show(t.getMessage());

                    }
                }
            });
        }

    }

    boolean isRequestFavorite = false;

    private void doFavorite() {
        if (!LoginManager.isLogin()) {
            LoginPage.start();
            return;
        }
        if (moment == null || mineBackup == null) {
            return;
        }
        boolean isFavorited = mineBackup.isFavorited();
        if (isRequestFavorite) {
            return;
        }
        isRequestFavorite = true;
        if (!isFavorited) {
            FavoriteRecord favoriteRecord = FavoriteRecord.newBuilder().momentId(moment.getId()).momentSubject(moment.getSubject()).momentTags(moment.getTags()).momentTitle(moment.getTitle()).build();
            (new FavoriteRequest()).addFavorite(favoriteRecord).enqueue(new Callback<ResponseBody>() {

                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    isRequestFavorite = false;
                    if (response.isSuccessful()) {
                        try {
                            String json = response.body().string();
                            FavoriteRecord favoriteRecord1 = JSON.parseObject(json, FavoriteRecord.class);
                            if (favoriteRecord1 != null && !isNull(favoriteRecord1.getId())) {
                                statisticsBackup.setFavoriteCount(statisticsBackup.getFavoriteCount() + 1);
                                mineBackup.setFavoriteId(favoriteRecord1.getId());
                                ivFavourite.setSelected(mineBackup.isFavorited());
                                tvFavoriteCount.setText(getCountValue(statisticsBackup.getFavoriteCount()));
                                tvFavoriteCount.setSelected(mineBackup.isFavorited());
                            }
                        } catch (IOException e) {

                        }
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    isRequestFavorite = false;
                }
            });
        } else {
            (new FavoriteRequest()).deleteFavorite(mineBackup.getFavoriteId()).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    isRequestFavorite = false;
                    if (response.isSuccessful()) {
                        statisticsBackup.setFavoriteCount(statisticsBackup.getFavoriteCount() - 1);
                        mineBackup.setFavoriteId(null);
                        ivFavourite.setSelected(mineBackup.isFavorited());
                        tvFavoriteCount.setText(getCountValue(statisticsBackup.getFavoriteCount()));
                        tvFavoriteCount.setSelected(mineBackup.isFavorited());
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    isRequestFavorite = false;
                    if (t != null && !TextUtils.isEmpty(t.getMessage())) {
                        ToastX.show(t.getMessage());
                    }
                }
            });
        }
    }

    private void doBuy() {
        if (moment != null) {
            PayUtil.pay(PayUtil.TYPE_LEARN_VIDEO, momentId, moment.getVersion(), new PayUtil.PayCallback() {
                @Override
                public void payed() {
                    // 刷新页面
                    requestData(true);
                }

                @Override
                public void momentChanged() {
                    // 刷新页面
                    requestData(true);
                }
            });
        }
//        if (!LoginManager.isLogin()) {
//            LoginPage.start();
//            return;
//        }
//        trackEvent.sendEvent(DetailPage.this, TrackEvent.DETAIL_PAGE_BUY, TrackEvent.DETAIL_PAGE_BUY_LABEL);
//        ARouter.getInstance()
//                .build(ARouterConfig.ConfirmOrderPage)
//                .withString("goodsId", moment.getId())
//                .withString("source", "app")
//                .withString("sourceUrl", ApiUrls.BaseUrl)
//                .navigation();

//        new AsyncTask<Object, Object, Object>() {
//            LoadingDialog loadingDialog;
//
//            @Override
//            protected void onPreExecute() {
//                loadingDialog = LoadingDialog.newBuilder()
//                        .with(DetailPage.this)
//                        .show();
//            }
//
//            @Override
//            protected Object doInBackground(Object... objects) {
//                try {
//                    Response<ResponseBody> response = ApiManager.getService().orderVerify(moment.getId()).execute();
//                    if (response.code() == ResponseCode.NOT_FOUND) {
//                        return null;
//                    } else if (response.code() == ResponseCode.OK) {
//                        String json = RetrofitUtil.getResponseBodyAsString(response);
//                        Order order = JSON.parseObject(json, Order.class);
//                        if (order.getStatus() == Order.Status.PAYED) {
//                            EventBus.getDefault().post(EventBuySuccess.newBuilder()
//                                    .goodsId(moment.getId())
//                                    .orderId(order.getId())
//                                    .build());
//                        }
//                        throw new Exception(StringUtils.getString(R.string.already_buy));
//                    } else {
//                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
//                    }
//                } catch (Exception e) {
//                    return e;
//                }
//            }
//
//            @Override
//            protected void onPostExecute(Object o) {
//                loadingDialog.dismiss();
//                if (o instanceof Exception) {
//                    ToastX.show(((Exception) o).getMessage());
//                } else {
//                    User user = AccountUtil.getCurrentUser();
//                    if (user != null && isNull(user.getMobile())) {
//                        ARouter.getInstance().build(ARouterConfig.BindingPhonePage).navigation();
//                        return;
//                    }
//                    trackEvent.sendEvent(DetailPage.this, TrackEvent.DETAIL_PAGE_BUY, TrackEvent.DETAIL_PAGE_BUY_LABEL);
//                    ARouter.getInstance()
//                            .build(ARouterConfig.ConfirmOrderPage)
//                            .withString("goodsId", moment.getId())
//                            .withString("source", "app")
//                            .withString("sourceUrl", ApiUrls.BaseUrl)
//                            .navigation();
//                }
//            }
//        }.execute();
    }

    @Override
    public void playChange(int position) {
//        if (mineBackup != null && !mineBackup.isBuyed()) {
//            ToastX.show(getString(R.string.pay_first));
//            return;
//        }
        for (int i = 0; i < mSelectionAdapter.getData().size(); i++) {
            (mSelectionAdapter.getData().get(i)).setSelected(position == i);
        }
        mSelectionAdapter.notifyDataSetChanged();
    }

    @Override
    public void buy() {
        doBuy();
    }

    @Override
    public void downloadVideos() {
        this.download();
    }

    @Override
    public void onPlaying() {

    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onError(int errorCode, String errorDetail) {

    }


    @Override
    public void orientation(boolean landscape) {
        setOrientation(landscape);
    }

    private void setOrientation(boolean landscape) {
        // 没有锁屏 才能旋转
        if (playerView != null && !playerView.isLock()) {
            playerView.orientationChange(landscape);
            inputLayout.setVisibility(landscape ? View.GONE : View.VISIBLE);
            if (landscape) {
                UIHelper.hideSystemUI(this);
                rlBack.setVisibility(View.INVISIBLE);
                ivShare.setVisibility(View.INVISIBLE);
            } else {
                rlBack.setVisibility(View.VISIBLE);
                ivShare.setVisibility(View.VISIBLE);
                UIHelper.showSystemUI(this);
            }
        }

//
//        if (playerView != null && !playerView.isVerticalVideo()) {
//
//        }
    }

    private List<String> getTagValue(String groupType) {
        List<String> valueList = new ArrayList<>();
        List<TagBackup> tagBackupList = moment.getTags();
        if (TextUtils.isEmpty(groupType) || tagBackupList == null
                || tagBackupList.isEmpty()) {
            return null;
        }
        for (TagBackup tag : tagBackupList) {
            if (tag == null) continue;
            if (!TextUtils.isEmpty(tag.getGroupType())
                    && groupType.equals(tag.getGroupType())) {
                valueList.add(tag.getName());
            }
        }
        return valueList;
    }

    private String getTextViewString(List<String> list) {
        if (list == null || list.isEmpty()) {
            return "";
        }
        StringBuffer sb = new StringBuffer(32);
        for (String string : list) {
            if (sb.length() == 0) {
                sb.append(string);
            } else {
                sb.append(" " + string);
            }
        }
        return sb.toString();
    }

    //    UserPage asd;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_share:
                if (moment != null && !isNull(moment.getWebUrl())) {
                    ShareDialog.newInstance(this).shareMoment(moment);
                } else {
                    ToastX.show(getString(R.string.share_url_invalid));
                }
                break;
            case R.id.rl_download:
                download();
                break;
            case R.id.rl_back:
                finish();
                break;
            case R.id.iv_comment:
                UIHelper.scrollToView(cdv.getRecyclerView(), tvCommentTitle);
                break;
            case R.id.tv_input:
                comment(null, null);
                break;
        }
    }


    private void download() {
        if (!LoginManager.isLogin()) {
            LoginManager.getInstance().startLoginActivity();
            return;
        }
        if (moment != null && moment.getSubject().equals(Subject.video_course)
                && (mineBackup == null || !mineBackup.isBuyed())) {
            ToastX.show(getString(R.string.pay_first));
            return;
        }
        if (DownloadUtil.getDownloadModelByGoodsId(moment.getId()) == null) {
            DownloadUtil.downloadVideo(this, moment.getId(), source, resourceId);
        } else {
            ToastX.show(getString(R.string.video_downloaded));
        }
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {
        if (moment != null) {//为了适配从已买进来的页面。直接传的是momet
            return GetCommentsRequest.newBuilder().pageNum((int) currentPage).goodsId(moment.getId()).build();
        } else {
            return GetCommentsRequest.newBuilder().pageNum((int) currentPage).goodsId(momentId).build();
        }
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            isRequestOkForComment = true;
            if (isRequestOkForDetail) {
                hideLoading();
                headerView.setVisibility(View.VISIBLE);
                playerParentLayout.setVisibility(View.VISIBLE);
                inputLayout.setVisibility(View.VISIBLE);
                cdv.setVisibility(View.VISIBLE);
                vLoading.setVisibility(View.GONE);
            }
            CommentResponse response = JSON.parseObject(respJson, CommentResponse.class);
            if (response != null && !ListUtil.isEmpty(response.getContent())) {
                resultList.addAll(response.getContent());
                return new CommonDataView.HandleResult(response.isLast());
            } else {
                return new CommonDataView.HandleResult(true);
            }
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }


    private String getVideoDuration() {
        if (videoCourse != null && !ListUtil.isEmpty(videoCourse.getVideos())) {
            long videoDuration = 0;
            for (SingleVideo videoEntity : videoCourse.getVideos()) {
                if (videoEntity != null) {
                    videoDuration = videoDuration + videoEntity.getDuration();
                }
            }
            return StringUtils.formatMediaDurationMS(videoDuration);
        } else {
            return "";
        }
    }


    /**
     * 把免费的视频遍历一下 放在最前面
     *
     * @param list
     */
    private void convertVideo(List<SingleVideo> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        // 2018.02.09最新需求。 自己的和已买，都是不复制免费，且可以直接看。没有免费字样。已经买过的从已买进去，依然从服务器获取
        boolean isBuyed = false;
        if (mineBackup != null) {
            isBuyed = mineBackup.isBuyed();
        }
        if (isMySelf()) {
            isBuyed = true;
            mineBackup.setBuyed(1);
        }
        if (!isBuyed) {
            List<SingleVideo> list1 = new ArrayList<>();
            SingleVideo videoEntity;
            for (int i = 0; i < list.size(); i++) {
                videoEntity = list.get(i);
                if (videoEntity.isFree()) {
                    SingleVideo createdVideoEntity = new SingleVideo();
                    createdVideoEntity.setCover(videoEntity.getCover());
                    createdVideoEntity.setDuration(videoEntity.getDuration());
//                createdVideoEntity.setId(videoEntity.get);
                    createdVideoEntity.setFree(videoEntity.getFree());
//                createdVideoEntity.setStage(videoEntity.getStage());
                    createdVideoEntity.setTitle(videoEntity.getTitle());
                    createdVideoEntity.setUrl(videoEntity.getUrl());
                    list1.add(createdVideoEntity);
                    videoEntity.setFree(0);
                }
            }
            if (!list1.isEmpty()) {
                list.addAll(0, list1);
            }
            for (int i = 0; i < list.size(); i++) {
                SingleVideo singleVideo = list.get(i);
                singleVideo.setIndex((i + 1) - list1.size());
            }
        }
        //  已买筛选判断
        if (isBuyed) {
            for (int i = 0; i < list.size(); i++) {
                SingleVideo singleVideo = list.get(i);
                singleVideo.setIndex((i + 1));
                // 如果是自己的视频，则全部免费
                singleVideo.setFree(1);
                singleVideo.setBuyed(true);
            }
            return;
        }
    }

    @Override
    protected void onStop() {
        if (moment != null && playerView != null) {
            long currentPosition = playerView.getLastPlayPosition();
            int playIndex = playerView.getPlayIndex();
            UserDataManager.getInstance().updatePlayProgress(moment.getId(), playIndex + 1, currentPosition);
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
//        if (keyboardWatcher != null) {
//            keyboardWatcher.release();
//        }
        FloatEditorActivity.setDefaultValue(null);
        TraceUtil.pop();
        super.onDestroy();
    }


    public class AddFollowTask extends AsyncTask<Object, Object, Object> {
//        LoadingDialog loadingDialog;

        @Override
        protected void onPreExecute() {
//            loadingDialog = LoadingDialog.newBuilder()
//                    .with(DetailPage.this)
//                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().addFollow(Follow.newBuilder()
                        .beFollowedId(moment.getCreatorBackup().getId())
                        .followerId(AccountUtil.getCurrentUser().getId())
                        .build())
                        .execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                Follow follow = JSON.parseObject(json, Follow.class);
                if (follow == null) {
                    throw new Exception(StringUtils.getString(R.string.add_follow_failed));
                }
                return new Follow(follow);
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
//            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
//                ToastX.show(R.string.add_follow_success);
                Follow follow = (Follow) o;
                moment.getMineBackup().setUserFollowId(follow.getId());
                moment.getMineBackup().setMutualFollower(follow.getMutualFollower());
                if (follow.getMutualFollower()) {
                    showMutualFollowedLayout();
                } else {
                    showFollowedLayout();
                }
                rlAttentionTv.setText(R.string.followed);
                rlAttentionTv.setBackgroundResource(R.drawable.light_green_button_bg);
                rlAttentionTv.setTextColor(ContextCompat.getColor(DetailPage.this, R.color.zwcolor_pink_f93684));
                rlAttentionTvTemp.setText(R.string.followed);
                rlAttentionTvTemp.setBackgroundResource(R.drawable.light_green_button_bg);
                rlAttentionTvTemp.setTextColor(ContextCompat.getColor(DetailPage.this, R.color.zwcolor_pink_f93684));
            }
        }
    }

    public class DeleteFollowTask extends AsyncTask<Object, Object, Object> {
//        LoadingDialog loadingDialog;

        @Override
        protected void onPreExecute() {
//            loadingDialog = LoadingDialog.newBuilder()
//                    .with(DetailPage.this)
//                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .deleteFollow(moment.getMineBackup().getUserFollowId())
                        .execute();
                if (response.code() != ResponseCode.NO_CONTENT) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
//            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                moment.getMineBackup().setUserFollowId("");
                rlAttentionTv.setText(R.string.follow);
                rlAttentionTv.setBackgroundResource(R.drawable.button_bg);
                rlAttentionTv.setTextColor(ContextCompat.getColor(DetailPage.this, R.color.white));
                rlAttentionTvTemp.setText(R.string.follow);
                rlAttentionTvTemp.setBackgroundResource(R.drawable.button_bg);
                rlAttentionTvTemp.setTextColor(ContextCompat.getColor(DetailPage.this, R.color.white));
                showFollowLayout();
            }
        }
    }

    public String getInterestStr(List<TagBackup> tagBackupList) {
        if (ListUtil.isEmpty(tagBackupList)) return "";
        List<TagBackup> avocationList = new LinkedList<>();
        for (TagBackup tagBackup : tagBackupList) {
            if (SetupUtil.GROUP_TYPE_AVOCATION.equals(tagBackup.getGroupType())) {
                avocationList.add(tagBackup);
            }
        }
        if (ListUtil.isEmpty(avocationList)) return "";
        try {
            StringBuilder stringBuilder = new StringBuilder();
            Iterator<TagBackup> iterator = avocationList.iterator();
            TagBackup first = iterator.next();
            stringBuilder.append(first.getName());
            while (iterator.hasNext()) {
                TagBackup item = iterator.next();
                stringBuilder.append("、").append(item.getName());
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            return "";
        }
    }

    private String getSellerAccid() {
        if (moment != null && moment.getCreatorBackup() != null && !isNull(moment.getCreatorBackup().getAccid())) {
            return moment.getCreatorBackup().getAccid();
        }
        return null;
    }

    public void showFollowLayout() {
        followLayout.setVisibility(View.VISIBLE);
        followLayoutTemp.setVisibility(View.VISIBLE);
        followedLayout.setVisibility(View.GONE);
        followedLayoutTemp.setVisibility(View.GONE);
        mutualfollowedLayout.setVisibility(View.GONE);
        mutualfollowedLayoutTemp.setVisibility(View.GONE);
    }

    public void showFollowedLayout() {
        followLayout.setVisibility(View.GONE);
        followLayoutTemp.setVisibility(View.GONE);
        followedLayout.setVisibility(View.VISIBLE);
        followedLayoutTemp.setVisibility(View.VISIBLE);
        mutualfollowedLayout.setVisibility(View.GONE);
        mutualfollowedLayoutTemp.setVisibility(View.GONE);
    }

    public void showMutualFollowedLayout() {
        followLayout.setVisibility(View.GONE);
        followLayoutTemp.setVisibility(View.GONE);
        followedLayout.setVisibility(View.GONE);
        followedLayoutTemp.setVisibility(View.GONE);
        mutualfollowedLayout.setVisibility(View.VISIBLE);
        mutualfollowedLayoutTemp.setVisibility(View.VISIBLE);
    }

}
